package com.zyz.filter;

import cn.hutool.json.JSONUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zyz.base.enums.ResponseCodeEnum;
import com.zyz.base.response.Message;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        // pre请求被路由之前  routing路由请求时  post再routing和error过滤器之后  error处理请求发生错误时
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext cxt = RequestContext.getCurrentContext();
        HttpServletRequest request = cxt.getRequest();

        String requestURI = request.getRequestURI();
        log.info("请求过滤 uri:{}", requestURI);

        // 权限过滤
        if (Objects.equals(requestURI, "/user/user/test1")) {
            cxt.setSendZuulResponse(false);
            cxt.setResponseBody(JSONUtil.toJsonStr(new Message<String>(ResponseCodeEnum.FORBIDDEN.getCode(), "forbidden")));
        }
        return null;
    }
}
